package com.swssm.waveloop;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.ShapeDrawable;
import android.util.Log;
import android.view.View;

public class WaveformView extends View {

	public ShapeDrawable sd;
	private int[] mData;
	private int mBeginFrame;
	private int mEndFrame;
	private int mHeight;
	private int mWidth;
	private float scaleX = 1f;
	private Paint mPaint;
	private Paint mPaintLine;
	private float numMax;
	
	public WaveformView(Context context) {
		super(context);
		
		//펜의 색
		mPaint = new Paint();
//		mPaint.setColor(0xff74AC23);
		
		//펜의 색
		mPaintLine = new Paint();
		mPaintLine.setColor(0xff74AC23);
		
		numMax = 0;
		
	}
	
	
	public void setData( int[] data, int beginFrame, int endFrame, int height )
	{
		mData = data;
		mBeginFrame = beginFrame;
		mEndFrame = endFrame;
		mHeight = height;
		mWidth = (int) ((mEndFrame-mBeginFrame)*2*scaleX);
		
		//여러번 불러지므로 한번만 불러지도록 수정해야함
		if(mData != null){
			//데이터의 최대값 구하기
			for(int i = 0 ; i < mData.length ; i++){
				if(numMax < mData[i]){
					numMax = mData[i];
				}
			}
		}
		
	}
	
	
	
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		
		Matrix matrix = canvas.getMatrix();
		matrix.postScale(1f, 1f);
		
		if(mData != null)
		{
			
//			int numRatio = 0;
			//들어온 데이터가 128보다 클때
			int	numRatio;
			int colorCctr;
			
			
			
			matrix.postTranslate(0, mHeight/2);
			//파형 matrix
			matrix.preScale(1, -1);
			canvas.setMatrix(matrix);
			
			//배열의 갯수만큼 
			for(int i = 0; i + mBeginFrame < mEndFrame; ++i){
				
				//nomalize
				if(numMax > 0){
					//최대 128까지
					numRatio = (int) Math.ceil(0xff / numMax);
					colorCctr = mData[i+mBeginFrame] * numRatio;
				}else{
					colorCctr = 0;
				}
				
				mPaint.setStrokeWidth(2);
				//red만 출력
				mPaint.setARGB(0xff, colorCctr, 0x00, 0x00);
				canvas.drawLine(i*2, 0, i*2, mHeight/2, mPaint);
			}
			
		}
		
		//세로 프레임 분리선
		canvas.drawLine(0, 0, 0, 50, mPaintLine);
		//가로 프레임 분리선
		canvas.drawLine(0, 0, mWidth, 0, mPaintLine);
		canvas.drawLine(0, 50, mWidth, 50, mPaintLine);
				
	}
	
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		setMeasuredDimension(mWidth, mHeight);
	}

	
}

